#include "student.h"
#include "dbmanager.h"
#include <QTableWidget>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QComboBox>
#include <QPushButton>
#include <QInputDialog>
#include <QMessageBox>
#include <QLineEdit>
#include <QSpinBox>
#include <QFormLayout>
#include <mysql.h>
#include <QLabel>

StudentManager::StudentManager(QWidget* parent) : QWidget(parent) {
    auto lay = new QVBoxLayout(this);
    auto topLay = new QHBoxLayout;

    m_table = new QTableWidget(0, 4);
    m_table->setHorizontalHeaderLabels({"ID", "姓名", "年龄", "班级"});
    m_table->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_table->setEditTriggers(QAbstractItemView::NoEditTriggers);

    m_classCombo = new QComboBox;
    m_classCombo->addItem("全部班级", -1);

    btnAdd  = new QPushButton("添加学生");
    btnEdit = new QPushButton("修改学生");
    btnDel  = new QPushButton("删除学生");

    topLay->addWidget(new QLabel("筛选班级："));
    topLay->addWidget(m_classCombo);
    topLay->addStretch();
    topLay->addWidget(btnAdd);
    topLay->addWidget(btnEdit);
    topLay->addWidget(btnDel);

    lay->addLayout(topLay);
    lay->addWidget(m_table);

    connect(btnAdd,  &QPushButton::clicked, this, &StudentManager::onAdd);
    connect(btnEdit, &QPushButton::clicked, this, &StudentManager::onEdit);
    connect(btnDel,  &QPushButton::clicked, this, &StudentManager::onDelete);
    connect(m_classCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &StudentManager::onClassFilterChanged);

    // 加载班级下拉框
    MYSQL_RES* res = DBManager::instance().query("SELECT id, name FROM class ORDER BY name");
    if (res) {
        while (MYSQL_ROW row = mysql_fetch_row(res)) {
            m_classCombo->addItem(row[1], QString(row[0]).toInt());
        }
        mysql_free_result(res);
    }

    refresh();
}

void StudentManager::refresh() {
    m_table->setRowCount(0);

    QString sql = "SELECT s.id, s.name, s.age, IFNULL(c.name, '无班级') "
                  "FROM student s LEFT JOIN class c ON s.class_id = c.id";

    int classId = m_classCombo->currentData().toInt();
    if (classId != -1) {
        sql += QString(" WHERE s.class_id = %1").arg(classId);
    }
    sql += " ORDER BY s.id";

    MYSQL_RES* res = DBManager::instance().query(sql);
    if (!res) return;

    while (MYSQL_ROW row = mysql_fetch_row(res)) {
        int r = m_table->rowCount();
        m_table->insertRow(r);
        m_table->setItem(r, 0, new QTableWidgetItem(row[0]));
        m_table->setItem(r, 1, new QTableWidgetItem(row[1]));
        m_table->setItem(r, 2, new QTableWidgetItem(row[2]));
        m_table->setItem(r, 3, new QTableWidgetItem(row[3]));
    }
    mysql_free_result(res);
    LOG << "学生列表刷新完成";
}

void StudentManager::onClassFilterChanged(int) {
    refresh();
}

void StudentManager::onAdd() {
    QDialog dlg(this);
    dlg.setWindowTitle("添加学生");
    auto lay = new QFormLayout(&dlg);

    auto leName = new QLineEdit;
    auto sbAge  = new QSpinBox; sbAge->setRange(10, 30);
    auto cbClass = new QComboBox;
    cbClass->addItem("无班级", 0);

    MYSQL_RES* res = DBManager::instance().query("SELECT id, name FROM class ORDER BY name");
    if (res) {
        while (MYSQL_ROW row = mysql_fetch_row(res)) {
            cbClass->addItem(row[1], QString(row[0]).toInt());
        }
        mysql_free_result(res);
    }

    lay->addRow("姓名：", leName);
    lay->addRow("年龄：", sbAge);
    lay->addRow("班级：", cbClass);

    auto btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(btnBox, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
    connect(btnBox, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
    lay->addRow(btnBox);

    if (dlg.exec() != QDialog::Accepted) return;
    if (leName->text().trimmed().isEmpty()) {
        QMessageBox::warning(this, "", "姓名不能为空");
        return;
    }

    QString classSql = cbClass->currentData().toInt() == 0 ? "NULL" : cbClass->currentData().toString();
    QString sql = QString("INSERT INTO student (name, age, class_id) VALUES ('%1', %2, %3)")
                      .arg(leName->text().trimmed())
                      .arg(sbAge->value())
                      .arg(classSql);

    if (DBManager::instance().exec(sql)) {
        refresh();
    }
}

void StudentManager::onEdit() {
    int row = m_table->currentRow();
    if (row < 0) { QMessageBox::information(this, "", "请先选择一个学生"); return; }

    QString id = m_table->item(row, 0)->text();

    QDialog dlg(this);
    dlg.setWindowTitle("修改学生");
    auto lay = new QFormLayout(&dlg);

    auto leName = new QLineEdit(m_table->item(row, 1)->text());
    auto sbAge  = new QSpinBox; sbAge->setRange(10, 30);
    sbAge->setValue(m_table->item(row, 2)->text().toInt());
    auto cbClass = new QComboBox;
    cbClass->addItem("无班级", 0);

    MYSQL_RES* res = DBManager::instance().query("SELECT id, name FROM class ORDER BY name");
    if (res) {
        while (MYSQL_ROW row = mysql_fetch_row(res)) {
            cbClass->addItem(row[1], QString(row[0]).toInt());
        }
        mysql_free_result(res);
    }
    // 设置当前班级
    cbClass->setCurrentText(m_table->item(row, 3)->text());

    lay->addRow("姓名：", leName);
    lay->addRow("年龄：", sbAge);
    lay->addRow("班级：", cbClass);

    auto btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    connect(btnBox, &QDialogButtonBox::accepted, &dlg, &QDialog::accept);
    connect(btnBox, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
    lay->addRow(btnBox);

    if (dlg.exec() != QDialog::Accepted) return;

    QString classSql = cbClass->currentData().toInt() == 0 ? "NULL" : cbClass->currentData().toString();
    QString sql = QString("UPDATE student SET name='%1', age=%2, class_id=%3 WHERE id=%4")
                      .arg(leName->text().trimmed())
                      .arg(sbAge->value())
                      .arg(classSql)
                      .arg(id);

    if (DBManager::instance().exec(sql)) {
        refresh();
    }
}

void StudentManager::onDelete() {
    int row = m_table->currentRow();
    if (row < 0) { QMessageBox::information(this, "", "请先选择一个学生"); return; }

    if (QMessageBox::question(this, "确认", "确定删除该学生吗？") == QMessageBox::Yes) {
        QString id = m_table->item(row, 0)->text();
        DBManager::instance().exec(QString("DELETE FROM student WHERE id=%1").arg(id));
        refresh();
    }
}
